<template>
  <div class="mapContainer" id="map">
    <EagleMap />
  </div>
</template>
<script>
//导入全局配置
import { ARCGIS_MAP_URL, BASE_DATA_URL } from "../../global";
//导入子组件
import EagleMap from "./EagleMap.vue";
//导入地图工具
import MapClass from "../../utils/MapClass";
import {
  polygonStyle,
  pointStyle,
  heightLightStyle,
} from "../../utils/MapUtils";
//导入openlayers部分依赖
import { Feature } from "ol";
import { MultiPolygon, Point } from "ol/geom";
//导入数据源
import shanghai from "/src/utils/data/shanghai";
import pointset from "/src/utils/data/pointset";
import axios from "axios";
//turf.js-地理计算工具类
import * as turf from "@turf/turf";

export default {
  name: "Map",
  components: {
    EagleMap,
  },
  data() {
    return {
      mapClass: undefined,
      overlayLayer: undefined,
      heightLightFeature: undefined,
      curFeatures: [],
    };
  },
  mounted() {
    this.mapClass = new MapClass("map", [121.4, 31.230416], "EPSG:4326");
    this.addEveneListenerForLoadData(); //注册监听事件
    //添加底图
    this.mapClass.addArcGISTileLayer(ARCGIS_MAP_URL, 0, {
      layerName: "sh_tileLayer",
      desc: "蓝黑底图",
    });
    //添加矢量行政区划图
    this.mapClass.addVectorLayer(0, polygonStyle, {
      layerName: "sh_vectorLayer",
      desc: "上海市行政区划图",
    });
    //添加标记点图层
    this.mapClass.addVectorLayer(0, pointStyle, {
      layerName: "sh_pointLayer",
      desc: "上海市标记点图",
    });
    //添加选中时高亮显示的矢量覆盖图层
    this.overlayLayer = this.mapClass.addOverlayLayer(heightLightStyle, {
      layerName: "heightLight_VecLayer",
      desc: "高亮显示-矢量图层",
    });
    this.getAreatData(); //初始化行政区划矢量图层
    //更新点图层
    //point-点图层
    let sh_point = this.getPointFeatures(pointset);
    this.mapClass.updateFeaturesByLayerName("sh_pointLayer", sh_point);
    //注册事件监听
    this.listenMapEvent();
    this.mapClass.addClusterVectorLayer(3, undefined, {
      layerName: "sh_clusterVecLayer",
      desc: "聚合图层",
    });
    // let features = this.createFeatures();

    // let layer = this.mapClass.getLayerByName("sh_clusterVecLayer");
    // layer.getSource().addFeatures(features);
    // console.log(layer);
  },
  methods: {
    addEveneListenerForLoadData() {
      this.mapClass.getOlMap().on("postrender", function (e) {
        console.log("load data ending");
      });
    },
    createFeatures() {
      let count = 2000;
      let features = new Array(count);
      let e = 4500000;
      for (let i = 0; i < count; ++i) {
        let coordinates = [4 * e * Math.random(), 2 * e * Math.random() - e];
        features[i] = new Feature(new Point(coordinates));
      }
      return features;
    },
    getAreatData(_code = "310000") {
      let _that = this;
      return axios({
        url: BASE_DATA_URL + _code + ".json",
        method: "GET",
      }).then(function (result) {
        let featuresRes = result.data["features"];
        // let features = _that.getMultiPolygonFeatures(featuresRes);
        _that.curFeatures = _that.getMultiPolygonFeatures(featuresRes);
        console.log(_that.curFeatures);
        //更新features
        _that.mapClass.updateFeaturesByLayerName(
          "sh_vectorLayer",
          _that.curFeatures
        );
      });
    },
    //注册鼠标移动事件
    listenMapEvent() {
      let _that = this;
      //鼠标移动事件
      this.mapClass.addEventListenerForLayer(
        "sh_vectorLayer",
        "pointermove",
        function (feature, pixel) {
          if (typeof feature !== "undefined") {
            //获取要素属性
            let featureCode = feature.get("code"),
              featureName = feature.get("name");
          }
          if (_that.heightLightFeature) {
            _that.overlayLayer
              .getSource()
              .removeFeature(_that.heightLightFeature);
          }
          if (feature) _that.overlayLayer.getSource().addFeature(feature);
          _that.heightLightFeature = feature;
        }
      );
      //鼠标点击事件
      this.mapClass.addEventListenerForLayer(
        "sh_vectorLayer",
        "singleclick",
        function (feature, event) {
          let coordinate = event.coordinate;
          // console.log(event);
          // console.log(feature);
          // console.log(_that.mapClass.getDefaultOverLay);
          let name = feature.get("name"),
            code = feature.get("code");
          _that.mapClass.setDefaultOverLay(
            coordinate,
            `<p> name : ${name}</p><p> code : ${code}</p>`
          );
        }
      );

      //注册地图移动后触发得事件
      this.mapClass.map.on("moveend", function (event) {
        //获取可视化区域得范围

        let bbox = _that.mapClass.map
          .getView()
          .calculateExtent(_that.mapClass.map.getSize());
        let bboxPolygon = turf.bboxPolygon(bbox);
        //计算结果数组
        let computeFeatureArray = new Array();
        console.log(bboxPolygon);
        _that.curFeatures.some(function (feature) {
          //判断是否相交
          console.log(feature);
          console.log(feature.getProperties().geometry);
          console.log(feature.getProperties());
          // turf.booleanCrosses(bboxPolygon, feature.getGeometry())
          //   ? computeFeatureArray.push(feature)
          //   : "";
        });
        //计算结果
        console.log(computeFeatureArray);
      });
    },
    /**
     * 获取features
     */
    getMultiPolygonFeatures(_featureCollection) {
      let features = new Array();
      if (!!_featureCollection == false) return features;
      //创建features
      for (let i = 0, len = _featureCollection.length; i < len; i++) {
        let properties = _featureCollection[i].properties;
        let geometry = _featureCollection[i].geometry;
        //创建Features
        let feature = new Feature({
          geometry: new MultiPolygon(geometry.coordinates),
        });
        //设置属性
        feature.set("name", properties["name"]);
        feature.set("code", properties["adcode"]);
        features.push(feature);
      }
      return features;
    },
    getPointFeatures(_featureCollection) {
      let features = new Array();
      if (!!_featureCollection == false) return features;
      //创建feature
      for (let i = 0, len = _featureCollection.length; i < len; i++) {
        let properties = _featureCollection[i].properties;
        let geometry = _featureCollection[i].geometry;
        //创建feature
        let feature = new Feature({
          geometry: new Point(geometry.coordinates),
        });
        //设置属性
        feature.set("name", "标记点" + i);
        features.push(feature);
      }
      return features;
    },
  },
};
</script>
<style scoped>
.mapContainer {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
}
</style>
